package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*全局异常处理器，处理项目中抛出的业务异常
 */


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    @ExceptionHandler
    public Result exceptionHander(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        String d =MessageConstant.UNKNOWN_ERROR;
        if(message.contains("Duplicate entry")){
            d = message.split(" ")[2];
            d= d+ MessageConstant.ALREADY_EXISTS;
            log.error("Duplicate entry :"+d);
        }

       return Result.error(d);
    }

}
